package com.hyt.it.ogt.kq.service.gov.arrange;

import com.alibaba.fastjson.JSON;
import com.hyt.core.base.BaseEntity;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.gov.enums.ProctorArrangeParamEnum;
import com.hyt.it.ogt.kq.service.gov.model.dto.ProgressResult;
import com.hyt.it.ogt.kq.service.gov.model.entity.Task;
import com.hyt.it.ogt.kq.service.gov.model.param.proctor.AutoProctorParam;
import com.hyt.it.ogt.kq.service.gov.model.vo.examiner.TimeRoomParamVO;
import com.hyt.progress.service.ProgressManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@Service
public class ProctorArrangeFactory extends ProctorArrangeAbstractService {
    @Resource
    private ProctorArrangeByLevelAdapter proctorArrangeByLevelAdapter;
    @Resource
    private ProctorArrangeByOfficeAdapter proctorArrangeByOfficeAdapter;
    @Resource
    private ProctorArrangeByRandomAdapter proctorArrangeByRandomAdapter;

    public ProctorArrangeFactory() {
    }

    /**
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void arrange(AutoProctorParam param) {
        //判断考生编排数据是否锁定
        this.checkLock(param);
        this.checkArrange(param);
        ProctorArrangeAbstractService service = this.getService(param);
        service.arrange(param);
        iTaskService.lambdaUpdate().set(Task::getProctorArrangeType, 1).set(Task::getProctorArrangeDate, LocalDateTime.now()).eq(BaseEntity::getId, param.getTaskId()).update();
        ProgressManager.finish(ProgressResult.builder().success(Boolean.TRUE).build());
    }

    public ProctorArrangeAbstractService getService(AutoProctorParam param) {
        Optional<TimeRoomParamVO> op = param.getTimeRoomParamVOList().stream().filter(item -> ProctorArrangeParamEnum.ARRANGE_RULE.getCode().equals(item.getCode())).findFirst();
        if ("0".equals(op.get().getValue())) {
            return proctorArrangeByOfficeAdapter;
        } else if ("1".equals(op.get().getValue())) {
            return proctorArrangeByLevelAdapter;
        } else if ("2".equals(op.get().getValue())) {
            return proctorArrangeByRandomAdapter;
        } else {
            log.error("不支持的监考员编排方式:{}", JSON.toJSONString(param));
            throw new KqException(ResponseCode.PROCTOR_DATA_LOCK_FALSE.getCode(), "不支持的监考员编排方式");
        }
    }
}
